package com.chenyu.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.chenyu.service.IUserService;
import com.chenyu.domain.User;
import com.chenyu.query.UserQuery;
import com.chenyu.util.AjaxResult;
import com.chenyu.util.PageList;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user" )
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user) {
        if ( user.getId() != null)
            userService.updateById(user);
            else
            userService.insert(user);
        return AjaxResult.success();
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value = "/{id}" )
    public AjaxResult delete(@PathVariable("id" ) Long id) {
            userService.deleteById(id);
        return AjaxResult.success();
    }

    //获取用户
    @GetMapping("/{id}" )
    public AjaxResult get(@PathVariable("id" ) Long id) {
        User user =userService.selectById(id);
        return AjaxResult.success(user);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping
    public AjaxResult list() {
        List< User> list = userService.selectList(null);
        return AjaxResult.success(list);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */

    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list" )
    public AjaxResult json(@RequestBody UserQuery query) {
        Page<User> page = new Page<User>(query.getPage(), query.getRows());
        page = userService.selectPage(page);
        PageList pageList = new PageList<User>(page.getTotal(), page.getRecords());
        return AjaxResult.success(pageList);
    }

    /**
     * 根据手机号获取用户
     * @param phone
     * @return
     */
    @GetMapping("/ph/{phone}")
    public AjaxResult getByPhone(@PathVariable String phone) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("phone", phone);
        return AjaxResult.success(userService.selectOne(wrapper));
    }



    @PostMapping("/register")
    @ApiOperation("用户注册")
    public AjaxResult register(@RequestBody Map<String,String> params){
        return userService.register(params);
    }
}
